package base2

import (
	"strings"
	"unicode/utf8"
)

type DateFormat struct {
}

// 支持yyyy-MM-dd HH:mm:SSS => 2006-01-02 15:30:000格式
func (d DateFormat) ConvertTimeFormat(format string) string {
	var builder strings.Builder
	builder.Grow(len(format) * 2) // 预分配足够空间

	for i := 0; i < len(format); {
		r, size := utf8.DecodeRuneInString(format[i:])
		i += size

		switch r {
		case 'y':
			if d.peek(format, i, 3) == "yyy" { // 检查是否"yyyy"
				builder.WriteString("2006")
				i += 3
			} else if d.peek(format, i, 1) == "y" { // 检查是否"yy"
				builder.WriteString("06")
				i += 1
			} else {
				builder.WriteRune(r)
			}
		case 'M':
			if d.peek(format, i, 1) == "M" { // 检查是否"MM"
				builder.WriteString("01")
				i += 1
			} else {
				builder.WriteString("1")
			}
		case 'd':
			if d.peek(format, i, 1) == "d" { // 检查是否"dd"
				builder.WriteString("02")
				i += 1
			} else {
				builder.WriteString("2")
			}
		case 'H':
			if d.peek(format, i, 1) == "H" { // 检查是否"HH"
				builder.WriteString("15")
				i += 1
			} else {
				builder.WriteString("15") // Go只有15表示24小时制
			}
		case 'h':
			if d.peek(format, i, 1) == "h" { // 检查是否"hh"
				builder.WriteString("03")
				i += 1
			} else {
				builder.WriteString("3")
			}
		case 'm':
			if d.peek(format, i, 1) == "m" { // 检查是否"mm"
				builder.WriteString("04")
				i += 1
			} else {
				builder.WriteString("4")
			}
		case 's':
			if d.peek(format, i, 1) == "s" { // 检查是否"ss"
				builder.WriteString("05")
				i += 1
			} else {
				builder.WriteString("5")
			}
		case 'a':
			builder.WriteString("PM")
		case 'S':
			if d.peek(format, i, 2) == "SS" { // 检查是否"SSS"
				builder.WriteString("000")
				i += 2
			} else {
				builder.WriteRune(r)
			}
		default:
			builder.WriteRune(r)
		}
	}

	return builder.String()
}

// peek 查看字符串中指定位置的内容
func (DateFormat) peek(s string, start, length int) string {
	if start+length > len(s) {
		return ""
	}
	return s[start : start+length]
}
